<template>
  <div v-loading="loading">
    <div id="ContainerId">
      <div class="page-container">
        <div class="fixed-container">
          <div class="fixed-content">
            <div class="panel-container">
              <div class="panel-content">
                <div class="panel-line space-between">
                  <div class="panel-left">
                    <el-radio-group v-model="tabActive" style="margin-right: 10px" size="mini" @change="handleChange">
                      <el-radio-button v-for="item in tabList" :key="item.id" :label="item.id">
                        {{ item.label }}
                        <i style="margin-left: 10px" @click.stop="handleEdit(item)" class="el-icon-edit-outline"></i>
                      </el-radio-button>
                    </el-radio-group>
                    <i class="el-icon-circle-plus-outline button-add" @click="handleAdd"></i>
                  </div>
                  <div class="panel-right">
                    {{ today }}
                    <i class="el-icon-camera" title="下载截图" @click="downloadImage"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="page-content">
          <el-row :gutter="10">
            <el-col :span="12" v-for="item in dataList" :key="item.title">
              <PanelChart chartType="pie" :title="item.title" :data="item.data" :typeList="['pie', 'bar']" />
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 添加弹窗 -->
    <el-dialog :title="current && current.id ? current.label : '新建自定义群体'" :visible.sync="showDialogAdd">
      <DialogAdd v-if="showDialogAdd" :id="current && current.id" @close="showDialogAdd = false" @success="handleAddSuccess" />
    </el-dialog>
  </div>
</template>

<script>
import domtoimage from 'dom-to-image'
import { apiAssetCls } from '@/api/index'
import { apiLabelGroupList, apiLabelGroupCount } from '@/api/dataStatistics'
import PanelChart from './components/PanelChart.vue'
import DialogAdd from './components/DialogAdd.vue'
import { parseTime } from '@/utils'

export default {
  name: 'GroupProfile',
  components: { PanelChart, DialogAdd },
  data() {
    return {
      today: parseTime(new Date(), '{y}.{m}.{d}'),
      tabActive: 0,
      tabList: [],
      apiAssetCls,
      showDialogAdd: false,
      dataList: [],
      current: null,
      containerId: 'ContainerId',
      loading: false,
      editModel: 'init',
    }
  },
  mounted() {
    this.init()
  },
  destroyed() {},
  methods: {
    init() {
      apiLabelGroupList().then((res) => {
        this.tabList = [
          ...res.data.map((item) => {
            return {
              id: item.id,
              label: item.name,
            }
          }),
        ]
        if (this.editModel === 'init') {
          if (this.tabList.length > 0) {
            this.tabActive = this.tabList[0].id
          }
        } else if (this.editModel === 'add') {
          this.tabActive = this.tabList[this.tabList.length - 1].id
        } else if (this.editModel === 'edit') {
          this.tabActive = this.current.id
        }
        this.handleChange()
      })
    },
    // tab点击
    handleChange() {
      this.current = this.tabList.find((item) => item.id === this.tabActive)
      apiLabelGroupCount({ id: this.tabActive }).then((res) => {
        this.dataList = []
        for (let key in res.data) {
          this.dataList.push({
            title: key,
            data: res.data[key],
          })
        }
      })
    },
    handleAdd() {
      this.current = null
      this.editModel = 'add'
      this.showDialogAdd = true
    },
    handleAddSuccess() {
      this.showDialogAdd = false
      this.init()
    },
    handleEdit(item) {
      this.current = item
      this.editModel = 'edit'
      this.showDialogAdd = true
    },
    // domtoimage生成base64图片
    downloadImage() {
      // 下载图片
      this.loading = true
      let node = document.getElementById(this.containerId)
      let that = this
      domtoimage
        .toPng(node, { bgcolor: '#f0f1f4' })
        .then(function (dataUrl) {
          that.downloadFileByBase64(dataUrl, `${that.current.label}-${that.today}.png`)
          that.$message({
            message: '生成成功！',
            type: 'success',
          })
          that.loading = false
        })
        .catch(function (error) {
          console.error('生成失败', error)
          that.$message({
            message: '生成失败！',
            type: 'fail',
          })
          that.loading = false
        })
    },
    base64toBlob(base64) {
      var arr = base64.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    downloadFile(url, name) {
      var a = document.createElement('a') //新建一个a链接
      a.setAttribute('href', url) // a链接的url为图片的url
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      let clickEvent = document.createEvent('MouseEvents')
      clickEvent.initEvent('click', true, true)
      a.dispatchEvent(clickEvent)
    },
    downloadFileByBase64(base64, name) {
      var myBlob = this.base64toBlob(base64)
      var myUrl = URL.createObjectURL(myBlob) //创建图片的临时url
      this.downloadFile(myUrl, name)
    },
  },
}
</script>

<style scoped lang="scss">
.page-content {
  padding-top: 10px;
}
.button-add {
  font-size: 20px;
  color: #5db42c;
  cursor: pointer;
  border-radius: 50%;
  &:hover {
    opacity: 0.8;
  }
}
.panel-left {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.panel-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  color: #333333;
}
.el-icon-camera {
  font-size: 20px;
  margin-left: 6px;
  cursor: pointer;
  margin-top: -4px;
  &:hover {
    color: #5db42c;
  }
}
</style>
